package middleware

import (
	"strings"
	"time"

	"device-admin/config/mysql"
	"device-admin/internal/models"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// DeviceOnlineCheck 在线检测
func DeviceOnlineCheck() gin.HandlerFunc {
	return func(c *gin.Context) {
		// tts快捷回复，不进行设备在线检测
		if strings.Contains(c.Request.URL.Path, "quick-reply") {
			return
		}
		var params struct {
			RobotID string `json:"robot_id"`
		}
		c.ShouldBindBodyWith(&params, binding.JSON)
		if params.RobotID == "" {
			params.RobotID = c.Query("robot_id")
		}
		if params.RobotID == "" {
			response.JSON(c, nil, errorx.New("设备id不能为空", -1))
			c.Abort()
			return
		}
		robots := strings.Split(params.RobotID, ",")
		for _, robotID := range robots {
			var device models.Device
			rowsAffected := mysql.NewDB().Model(&models.Device{}).
				Where(&models.Device{
					RobotID: robotID,
				}).
				Take(&device).
				RowsAffected
			c.Set("device_firmware_version", device.FirmwareVersion)

			if rowsAffected <= 0 {
				response.JSON(c, nil, errorx.New(robotID+"设备不存在", -1))
				c.Abort()
				return
			}
			if time.Now().Unix()-device.LatestActiveTime > 60 {
				response.JSON(c, nil, errorx.New(robotID+"-95不在线", -1))
				c.Abort()
				return
			}
		}
	}
}

// Device97OnlineCheck 97售卖状态监测
func Device97OnlineCheck() gin.HandlerFunc {
	return func(c *gin.Context) {
		var params struct {
			RobotID string `json:"robot_id"`
		}
		c.ShouldBindBodyWith(&params, binding.JSON)
		if params.RobotID == "" {
			params.RobotID = c.Query("robot_id")
		}
		if params.RobotID == "" {
			response.JSON(c, nil, errorx.New("设备id不能为空", -1))
			c.Abort()
			return
		}
		robots := strings.Split(params.RobotID, ",")
		for _, robotID := range robots {
			var terminal models.Terminal
			rowsAffected := mysql.NewDB().Model(&models.Terminal{}).
				Where("robot_id = ?", params.RobotID).
				Where("terminal_type = ?", "97").
				Take(&terminal).
				RowsAffected

			if rowsAffected <= 0 {
				response.JSON(c, nil, errorx.New(robotID+"-97设备不存在", -1))
				c.Abort()
				return
			}
			if time.Now().Unix()-terminal.LatestActiveTime > 60 {
				response.JSON(c, nil, errorx.New(robotID+"-97设备不在线", -1))
				c.Abort()
				return
			}
		}
	}
}
